<template>
  <div class="approval approvalEditor-wrapper">
    <div class="header">
      <span class="span-box">
        <span class="backIcon white" @click="goOut">
          <a-icon class="fs22" type="left" />
        </span>
        <a-tooltip placement="bottomLeft">
          <template slot="title">
            <span>{{ baseinfo.typeName || "空模板" }}</span>
          </template>
          <span class="empy white ove">{{ baseinfo.typeName || "空模板" }}</span>
        </a-tooltip>
      </span>
      <span class="tabs">
        <span :class="defaultTabs == 1 ? 'isActive' : ''" @click="saveData(1)">
          <i class="order-number">1</i>基础设置
          <div v-if="defaultTabs == 1" style=" width: 80%; height: 3px; background:#ffffff;margin: 0 auto; margin-top: -10px;"></div>
        </span>
        <span :class="defaultTabs == 2 ? 'isActive' : ''" @click="saveData(2)">
          <i class="order-number">2</i>表单设计
          <div v-if="defaultTabs == 2" style=" width: 80%; height: 3px; background:#ffffff;margin: 0 auto; margin-top: -10px;"></div>
        </span>
        <span :class="defaultTabs == 3 ? 'isActive' : ''" @click="saveData(3)">
          <i class="order-number">3</i>流程设计
          <div v-if="defaultTabs == 3" style=" width: 80%; height: 3px; background:#ffffff;margin: 0 auto; margin-top: -10px;"></div>
        </span>
        <span :class="defaultTabs == 4 ? 'isActive' : ''" @click="saveData(4)">
          <i class="order-number">4</i>高级设置
          <div v-if="defaultTabs == 4" style=" width: 80%; height: 3px; background:#ffffff;margin: 0 auto; margin-top: -10px;"></div>
        </span>
      </span>
      <a-button size="large" class="fr text_color_o mr16" @click="saveData(null)">发布</a-button>
    </div>
    <div class="approvalEditor-content">
      <BaseSet v-show="defaultTabs === 1" v-model="baseinfo" @formTypeChange="onFormTypeChange" />
      <FormSet ref="formSet" v-show="defaultTabs === 2" v-model="formlist" @change="onFormListChange" />
      <ProcessSet v-show="defaultTabs === 3" v-model="process" :setProcess="process" :formlist="formlist" />
      <SeniorSet v-show="defaultTabs === 4" v-model="setting" />
    </div>
  </div>
</template>

<script>
import BaseSet from "./components/setters/BaseSet";
import FormSet from "./components/setters/FormSet";
import ProcessSet from "./components/setters/ProcessSet";
import SeniorSet from "./components/setters/SeniorSet";
import { publishApproval, getApprovalDetail } from "../api";
import { isJson, isContainByString } from "@/utils/index";
export default {
  components: { BaseSet, FormSet, ProcessSet, SeniorSet },
  data() {
    return {
      blockList: [],
      baseinfo: {
        // 基础设置
        isSysStart: "",
        id: null,
        typeName: "", // 审批名称
        groupId: "", // 审批分组
        type: "", // 审批类型
        revokeType: "", // 撤回方式
        icon: "https://res.csxr.cn/icon/approval/baoxiao.png", // 审批图标
        typeDesc: "" // 审批说明
      },
      formlist: [], // 审批表单
      process: {
        // 审批流程
        name: "发起人",
        nodeType: "start",
        nodeId: 0,
        limitDepartment: "",
        limitUser: "",
        props: "",
        formSetting: []
      },
      setting: {
        // 高级设置
        id: null,
        flowId: null,
        uplicateRemoval: "",
        tipsRemake: "",
        remakeRequire: false,
        remakeEnableOther: false,
        remakeShow: true
      },
      defaultTabs: 1
    };
  },
  computed: {
    approFlowId() {
      return this.$route.query.id;
    }
  },
  mounted() {
    console.log("this.approFlowId", this.approFlowId);
    if (this.approFlowId) {
      getApprovalDetail(this.approFlowId)
        .then(res => {
          const flow = res.data;
          this.baseinfo = {
            isSysStart: Number(flow.isSysStart),
            id: flow.id,
            typeName: flow.typeName,
            groupId: flow.groupId,
            type: flow.type,
            revokeType: flow.revokeType,
            icon: flow.icon,
            typeDesc: flow.typeDesc
          };
          if (flow.flowForm && flow.flowForm.length) {
            this.formlist = JSON.parse(flow.flowForm).map(item =>
              Object.assign({}, item, {
                props: JSON.parse(item.props)
              })
            );
          } else {
            flow.flowForm = [];
          }
          this.process = this.buildFormPowerList(flow.process);
          this.setting = {
            id: flow.setting.id,
            flowId: flow.setting.flowId,
            uplicateRemoval: flow.setting.uplicateRemoval,
            tipsRemake: flow.setting.tipsRemake,
            remakeRequire: flow.setting.remakeRequire,
            remakeEnableOther: flow.setting.remakeEnableOther,
            remakeShow: flow.setting.remakeShow
          };
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
    }
  },

  methods: {
    onFormTypeChange(data) {
      this.formlist = data;
    },
    onFormListChange(e) {
      this.blockList = e;
      this.process = this.buildFormPowerList(this.process);
    },
    goOut() {
      const _this = this;
      this.$confirm({
        title: "有修改的内容未发布，确认离开吗？",
        onOk() {
          _this.$router.go(-1);
        }
      });
    },
    saveData(type) {
      if (!this.baseinfo.typeName || !this.baseinfo.groupId || !this.baseinfo.type) {
        this.$message.error("基础设置中有必填项未填写");
        return;
      }
      const oldType = this.defaultTabs;
      this.defaultTabs = type;
      if (oldType === 2) this.$refs.formSet.handleFormDesignSave();
      if (!type) {
        this.defaultTabs = oldType;
        publishApproval({
          ...this.baseinfo,
          flowForm: this.formlist,
          process: this.process,
          setting: this.setting
        })
          .then(res => {
            this.$message.success("发布成功");
            if (isContainByString("newApprovalAdmin")) {
              this.$router.replace("approvalAdmin/setting");
            } else if (isContainByString("defaultTransferAccounts")) {
              this.$router.replace("/paySalary/examine");
            } else {
              this.$router.replace("approval/setting");
            }
          })
          .catch(err => {
            console.log("debug log --> ", err);
          });
      }
    },
    buildFormPowerList(data) {
      const dataTemp = Object.assign({}, data);
      this.buildProcessFormPower(dataTemp);
      return dataTemp;
    },
    buildProcessFormPower(data) {
      // 审批流表单权限
      if (isJson(data.props)) {
        data.props = JSON.parse(data.props);
      }
      const hasFormSetting = data.formSetting && data.formSetting.length && data.formSetting.length > 0;
      if (data.nodeType !== "notifier" && data.nodeType !== "block" && data.nodeType !== "condition" && hasFormSetting) {
        if (isJson(data.formSetting)) {
          data.formSetting = JSON.parse(data.formSetting);
        }
        const formCodes = data.formSetting.map(f => f.formCode);
        const formPowers = [];
        this.formlist.map(item => {
          if (formCodes.includes(item.code)) {
            const form = data.formSetting.find(f => f.formCode === item.code);
            if (form) {
              formPowers.push(form);
            }
          } else {
            formPowers.push({
              formCode: item.code,
              flowFormName: item.label,
              sort: item.sort,
              type: data.nodeType === "start" ? "edit" : "read"
            });
          }
        });
        data.formSetting = formPowers;
      }
      if (data.childNode) {
        const childNodeTemp = Object.assign({}, data.childNode);
        this.buildProcessFormPower(childNodeTemp);
        data.childNode = childNodeTemp;
      }
      if (data.conditionNodes) {
        data.conditionNodes.map(item => {
          if (item.childNode) {
            const itemChildNodeTemp = Object.assign({}, item.childNode);
            this.buildProcessFormPower(itemChildNodeTemp);
            item.childNode = itemChildNodeTemp;
          }
        });
      }
    }
  }
};
</script>
<style lang="scss">
@import "./styles/index.scss";
</style>
